package com.lxy.elasticsearch100.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * <p>
 * Elasticsearch配置
 * </p>
 *
 * @author Administrator
 * @since 2024/10/30
 */
@Configuration
public class ElasticsearchConfig {

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        // 设置主机地址和端口
        final String hostname = "192.168.200.144";
        final int port = 9200;
        // 设置用户名和密码
        final String username = "elastic";
        final String password = "0zrJBU*o2KCH@f*&paj";
        // 创建凭证提供者
        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        // 创建RestClientBuilder
        RestClientBuilder builder = RestClient.builder(new HttpHost(hostname, port))
                .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
        // 创建RestHighLevelClient实例
        return new RestHighLevelClient(builder);
    }

}
